package com.jiuli.liping.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jiuli.liping.dao.OnDutyHisDao;
import com.jiuli.liping.dao.UserlistDao;
import com.jiuli.liping.service.OnDutyHisService;
import com.jiuli.liping.util.DateUtils;
import com.jiuli.liping.util.WeiXinUtils;
import com.jiuli.liping.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class OnDutyHisServiceImpl implements OnDutyHisService {
    @Value("${file_hostpath2}")
    private String fileHostPath2;
    @Autowired
    private OnDutyHisDao onDutyHisDao;
    @Autowired
    private UserlistDao userlistDao;
    @Override
    @Transactional
    public int updateOnDutyHis(OnDutyHis onDutyHis) {
        if(onDutyHis.getImgs() != null) {
            for (String img : onDutyHis.getImgs()) {
                onDutyHisDao.insertImg(onDutyHis.getId(), img);
            }
        }
        return onDutyHisDao.updateOnDutyHis(onDutyHis);
    }

    @Override
    public OnDutyHis getOnDutyHis(String code) {

        OnDutyHis his = onDutyHisDao.getOnDutyHis(code);
        return his;
    }

    @Override
    public String upload(MultipartFile blobFile) {
        Message mess=new Message();
        String dir = fileHostPath2+"/chushihua.text";
        File fileDir = new File(dir);
        if(!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        File file = new File(fileHostPath2+"/"+fileName);

        String url="";
        try {
            blobFile.transferTo(file);
            url = "http://api.jiuli.com:8070/zbimg/"+fileName;
        } catch (Exception e) {
            e.printStackTrace();
            url ="error";
        }
        return url;
    }

    /**
     * 定时任务
     * 方法关闭
     */
    @Override
    @Transactional
    @Scheduled(cron = "0 0 10 * * ?")
    //@Scheduled(cron = "0 0/1 * * * ? ")
    public int zbMessage(){
        List<OnDutyHis> his = onDutyHisDao.getZb();
        for (OnDutyHis odh: his) {
            String code = odh.getCode();
            if(code==null){
                continue;
            }
            String wecharId = userlistDao.getWecharIdWx(String.format("%05d", Integer.valueOf(code)))+"";
            JSONObject jsonss = null;
            try {
                String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=M2Z_Rj9hwoLz3pc_aB-qdc1ILnv7G3IhbSHNCXZFaYA";
                jsonss = WeiXinUtils.getWeiXinApi(urls);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //获得token    json串开始
            String token = jsonss.toString();
            //解析json
            JSONObject json = JSONObject.parseObject(token);
            AccessToken accessToken = new AccessToken();
            accessToken.setAccess_token(json.getString("access_token"));
            //获得token    json串结束
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();

            String mes = odh.getName()+",你好！你在"+odh.getDate().split(" ")[0]+"值班！";
            String param2 = "{" +
                                    "\"touser\" :\""+wecharId+"\" ," +
                                    "\"msgtype\" : \"news\"," +
                                    "\"agentid\" : 1000057, "+
                                    "\"news\" : {" +
                                            "\"articles\" : ["+
                                                "{"+
                                                "\"title\" : \""+mes+"\", "+
                                                "\"description\" : \"点击确认\", "+
                                                "\"url\" : \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwef2fadef61221778&redirect_uri=http://api.jiuli.com:8070/zhiban?id="+odh.getId()+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect\", "+
                                                "\"picurl\" : \"http://api.jiuli.com:8070/zbimg/zhiban.png\", "+
                                                "\"btntxt\":\"更多\", "+
                                                "}"+
                                            "]"+
                                        "}"+
                           "}";

            String json1 = WeiXinUtils.getWeiXinApiPost(urls, param2);
            String status = "1";
            int b = onDutyHisDao.updatestatus(status,odh.getId());
            int a =0;
        }
        return 0;
    }

    @Override
    @Transactional
    @Scheduled(cron = "0 0 17 * * ? ")
    public int zbMessageStart() {
        List<OnDutyHis> his = onDutyHisDao.getZbStart();
        for (OnDutyHis odh: his) {
            String code = odh.getCode();
            if(code==null){
                continue;
            }
            String wecharId = userlistDao.getWecharIdWx(String.format("%05d", Integer.valueOf(code)))+"";
            JSONObject jsonss = null;
            try {
                String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=M2Z_Rj9hwoLz3pc_aB-qdc1ILnv7G3IhbSHNCXZFaYA";
                jsonss = WeiXinUtils.getWeiXinApi(urls);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //获得token    json串开始
            String token = jsonss.toString();
            //解析json
            JSONObject json = JSONObject.parseObject(token);
            AccessToken accessToken = new AccessToken();
            accessToken.setAccess_token(json.getString("access_token"));
            //获得token    json串结束
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();

            String mes = odh.getName()+",你好！你在"+odh.getDate().split(" ")[0]+"的值班任务即将开始,请确认";
            String param2 = "{" +
                    "\"touser\" :\""+wecharId+"\" ," +
                    "\"msgtype\" : \"news\"," +
                    "\"agentid\" : 1000057, "+
                    "\"news\" : {" +
                    "\"articles\" : ["+
                    "{"+
                    "\"title\" : \""+mes+"\", "+
                    "\"description\" : \"点击确认\", "+
                    "\"url\" : \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwef2fadef61221778&redirect_uri=http://api.jiuli.com:8070/zhiban?id="+odh.getId()+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect\", "+
                    "\"picurl\" : \"http://api.jiuli.com:8070/zbimg/zhiban.png\", "+
                    "\"btntxt\":\"更多\", "+
                    "}"+
                    "]"+
                    "}"+
                    "}";

            String json1 = WeiXinUtils.getWeiXinApiPost(urls, param2);
            String status = "1";

        }
        return 0;
    }

    /**
     * 定时任务
     * 保证链接失效性
     */
    @Transactional
    @Scheduled(cron = "0 0 16 * * ?")
    //@Scheduled(cron = "0 0/1 * * * ? ")
    public int dsMessage() {
        onDutyHisDao.updateHisAllFlag();
        onDutyHisDao.updateAllFlag();
        return 0;
    }

    @Override
    public int updateTrue(OnDutyHis onDutyHis) {
        int a = onDutyHisDao.selectCountOdh(onDutyHis);
        if(a==1){
            onDutyHisDao.updatestatus("2",onDutyHis.getId());
        }else{
            return 1;
        }
        return 1;
    }

    @Override
    public Message deleteImg(String imgName) {
        Message mess=new Message();
        String[] split = imgName.split("/");
        File file = new File(fileHostPath2+"/"+split[4]);
        if (file.exists()) {//文件是否存在
            if (file.delete()) {//存在就删了，返回1
                mess.setMessage("删除成功");
            } else {
                mess.setMessage("删除失败");
            }
        }else{
            mess.setMessage("文件不存在");
        }
        mess.setFlag("success");
        return mess;
    }

    @Override
    public Location getLocation(Location location) {
        JSONObject jsonss = null;
        try {
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=M2Z_Rj9hwoLz3pc_aB-qdc1ILnv7G3IhbSHNCXZFaYA";
            jsonss = WeiXinUtils.getWeiXinApi(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获得token    json串开始
        String token = jsonss.toString();
        //解析json
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls2 = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token="+accessToken.getAccess_token();
        JSONObject jsonss2 = null;
        try {
            jsonss2 = WeiXinUtils.getWeiXinApi(urls2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String ticket2 = jsonss2.toString();
        JSONObject json2 = JSONObject.parseObject(ticket2);
        //获得ticket
        String ticket = json2.getString("ticket");
        //获取随机字符串
        String sj = OnDutyHisServiceImpl.getRandomString(9);
        //获取时间戳
        String startTs = System.currentTimeMillis()+"";
        String all = "jsapi_ticket="+ticket+"&noncestr="+sj+"&timestamp="+startTs+"&url="+location.getUrl();
        String sha = OnDutyHisServiceImpl.getSha1(all);
        Location lo = new Location();
        lo.setSignature(sha);
        lo.setCorpid("wwef2fadef61221778");
        lo.setNoncestr(sj);
        lo.setTimestamp(startTs);
        lo.setUrl(location.getUrl());
        return lo;
    }

    @Override
    public OnDutyHis selectOdh(OnDutyHis onDutyHis) {
        return onDutyHisDao.selectOdh(onDutyHis);
    }

    @Override
    public Address getAddress(String location) {
        JSONObject jsonss = null;
        Address ad = new Address();
        try {
            String urls = "https://apis.map.qq.com/ws/geocoder/v1/?location="+location+"&key=US4BZ-4W36U-FW2VU-4NMM7-5TL3K-R3BP5&get_poi=0";
            jsonss = WeiXinUtils.getWeiXinApiLocation(urls);
            String address = jsonss.toString();
            //解析json
            JSONObject json = JSONObject.parseObject(address);
            JSONObject json1 = JSONObject.parseObject(json.getString("result"));
            JSONObject json2 = JSONObject.parseObject(json1.getString("formatted_addresses"));
            ad.setRecommend(json2.getString("recommend"));
            ad.setRough(json2.getString("rough"));
            ad.setAddress(json1.getString("address"));
            ad.setFlag("success");
        } catch (IOException e) {
            ad.setFlag("failed");
            e.printStackTrace();
        }
        return ad;
    }

    @Override
    public List<OnDutyHis> getAllUserMonth(String code) {
        return onDutyHisDao.getAllUserMonth(code);
    }

    @Override
    @Transactional
    public String requestTb(String id1, String id2) {
        OnDutyHis odh = onDutyHisDao.selectOne(id1);
        OnDutyHis odh2 = onDutyHisDao.selectOne(id2);
        //往历史表插入调班记录数据
        OnDutyHistory his = new OnDutyHistory();
        int id = onDutyHisDao.getId();
        his.setIdOne(odh.getId()+"");
        his.setIdOneName(odh.getName());
        his.setIdOneDate(odh.getDate());
        his.setIdTwo(odh2.getId()+"");
        his.setIdTwoName(odh2.getName());
        his.setIdTwoDate(odh2.getDate());
        his.setId(id);
        his.setIdOneOrg(odh.getOrg());
        his.setIdTwoOrg(odh2.getOrg());
        onDutyHisDao.insertHistory(his);

        if("2".equals(odh.getFlagTwo())){
            return odh.getName()+"调班中,等待对方确认";
        }
        if("2".equals(odh2.getFlagTwo())){
            return odh2.getName()+"调班中,等待对方确认";
        }
        String code = onDutyHisDao.getCode(odh2.getIphone());
        String wecharId = userlistDao.getWecharIdWx(String.format("%05d", Integer.valueOf(code)))+"";
        JSONObject jsonss = null;
        try {
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=M2Z_Rj9hwoLz3pc_aB-qdc1ILnv7G3IhbSHNCXZFaYA";
            jsonss = WeiXinUtils.getWeiXinApi(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获得token    json串开始
        String token = jsonss.toString();
        //解析json
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();

        String mes = odh2.getName()+",你好！"+odh.getName()+"希望和你值班日期交换,他的值班日期为"+odh.getDate().split(" ")[0]+",同意请确认!";
        String param2 = "{" +
                "\"touser\" :\""+wecharId+"\" ," +
                "\"msgtype\" : \"news\"," +
                "\"agentid\" : 1000057, "+
                "\"news\" : {" +
                "\"articles\" : ["+
                "{"+
                "\"title\" : \""+mes+"\", "+
                "\"description\" : \"点击确认\", "+
                "\"url\" : \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwef2fadef61221778&redirect_uri=http://api.jiuli.com:8070/zhiban?id=h"+id+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect\", "+
                "\"picurl\" : \"http://api.jiuli.com:8070/zbimg/tb.jpg\", "+
                "\"btntxt\":\"更多\", "+
                "}"+
                "]"+
                "}"+
                "}";

        String json1 = WeiXinUtils.getWeiXinApiPost(urls, param2);

        //锁定这2个账户为调班中
        onDutyHisDao.updateFlag(id1);
        onDutyHisDao.updateFlag(id2);
        return "success";
    }

    @Override
    @Transactional
    public String arganRequestTb(String id1, String id2,String id3) {
        OnDutyHis odh = onDutyHisDao.selectOne(id1);
        OnDutyHis odh2 = onDutyHisDao.selectOne(id2);
        String code = onDutyHisDao.getCode(odh.getIphone());
        String wecharId = userlistDao.getWecharIdWx(String.format("%05d", Integer.valueOf(code)))+"";
        JSONObject jsonss = null;
        try {
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=M2Z_Rj9hwoLz3pc_aB-qdc1ILnv7G3IhbSHNCXZFaYA";
            jsonss = WeiXinUtils.getWeiXinApi(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获得token    json串开始
        String token = jsonss.toString();
        //解析json
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();

        String mes = odh.getName()+",你好！"+odh2.getName()+"已同意值班时间更换，请于"+odh2.getDate().split(" ")[0]+"准时值班！";
        String param = "{" +
                "\"touser\" :\"" + wecharId + "\" ," +
                "\"msgtype\" : \"text\", " +
                "\"agentid\" : 1000057, " +
                "\"text\" : { \"content\" : \"" + mes + "\" }," +
                "\"safe\" : 0, " +
                "\"enable_id_trans\" : 0, " +
                "\"enable_duplicate_check\" : 0, " +
                "}";

        String json1 = WeiXinUtils.getWeiXinApiPost(urls, param);

        //更换调班时间，并释放为flag为未调班中
        OnDutyHis oh=new OnDutyHis();
        oh.setId(odh.getId());
        oh.setDate(odh2.getDate());
        onDutyHisDao.updateDate(oh);
        OnDutyHis oh2=new OnDutyHis();
        oh2.setId(odh2.getId());
        oh2.setDate(odh.getDate());
        onDutyHisDao.updateDate(oh2);

        onDutyHisDao.updateHisFlag(id3);
        return "success";
    }

    @Override
    public OnDutyHis getUserMonth(String code) {
        Iphone phone = onDutyHisDao.getIphone(code);
        OnDutyHis his = onDutyHisDao.getUserMonth(phone.getMobileNo());
        OnDutyHis his2 = onDutyHisDao.getUserMonth(phone.getSortMNo());
        if(his == null){
            return his2;
        }else{
            return his;
        }
    }

    @Override
    public OnDutyHistory getZbById(String id) {
        OnDutyHistory od1 = onDutyHisDao.selectHistoryOne(id);
        return od1;
    }

    @Override
    @Transactional
    public String refuseRequestTb(String id1, String id2,String id3) {
        OnDutyHis odh = onDutyHisDao.selectOne(id1);
        OnDutyHis odh2 = onDutyHisDao.selectOne(id2);
        String code = onDutyHisDao.getCode(odh.getIphone());
        String wecharId = userlistDao.getWecharIdWx(String.format("%05d", Integer.valueOf(code)))+"";
        JSONObject jsonss = null;
        try {
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=M2Z_Rj9hwoLz3pc_aB-qdc1ILnv7G3IhbSHNCXZFaYA";
            jsonss = WeiXinUtils.getWeiXinApi(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获得token    json串开始
        String token = jsonss.toString();
        //解析json
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();

        String mes = odh.getName()+",你好！"+odh2.getName()+"拒绝值班时间更换，请照常值班或者重新选择交换值班人员！";
        String param = "{" +
                "\"touser\" :\"" + wecharId + "\" ," +
                "\"msgtype\" : \"text\", " +
                "\"agentid\" : 1000057, " +
                "\"text\" : { \"content\" : \"" + mes + "\" }," +
                "\"safe\" : 0, " +
                "\"enable_id_trans\" : 0, " +
                "\"enable_duplicate_check\" : 0, " +
                "}";

        String json1 = WeiXinUtils.getWeiXinApiPost(urls, param);

        //不更换调班时间，释放为flag为未调班中
        OnDutyHis oh=new OnDutyHis();
        oh.setId(odh.getId());
        oh.setDate(odh.getDate());
        onDutyHisDao.updateDate(oh);
        OnDutyHis oh2=new OnDutyHis();
        oh2.setId(odh2.getId());
        oh2.setDate(odh2.getDate());
        onDutyHisDao.updateDate(oh2);
        onDutyHisDao.updateHisFlag(id3);
        return "success";
    }

    @Override
    public List<OnDutyHis> getUserMonthBy30() {
        return onDutyHisDao.getUserMonthBy30();
    }

    @Override
    public List<OnDutyHis> getUserMonthByGr(String code) {
        Iphone phone = onDutyHisDao.getIphone(code);
        List<OnDutyHis> his = onDutyHisDao.getUserMonthByGr(phone.getMobileNo());
        List<OnDutyHis> his2 = onDutyHisDao.getUserMonthByGr(phone.getSortMNo());
        if(his == null){
            return his2;
        }else{
            return his;
        }
    }

    //length用户要求产生字符串的长度
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    //Sha1签名
    public static String getSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
}
